package com.kidala;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * Copyright (c) 2001 Timothy W Macinta, All Rights Reserved.<p>
 *
 * @author Tim Macinta (twm@alum.mit.edu)
 **/
public class TimeoutTest implements Runnable {

  // This method opens a URLConnection and attempts
  // to retrieve the InputStream for it.

  public static void main(String arg[]) {
    try {
      URL url = new URL(arg[0]);
      URLConnection ucon = url.openConnection();
      new TimeoutTest(ucon);
      InputStream in = ucon.getInputStream();
      System.out.println("Got the InputStream.");
      in.close();
    } catch (Exception e) {
      System.out.println("Caught an Exception.");
      e.printStackTrace();
    }
    System.out.println("Done.");
  }

  // This creates a thread which times out a URLConnection
  // after 10 seconds.

  URLConnection ucon;
  public TimeoutTest(URLConnection ucon) {
    this.ucon = ucon;
    new Thread(this).start();
  }

  public void run() {
    
    // sleep for 10 seconds
    
    long targ_time = System.currentTimeMillis() + 10 * 1000L;
    while (System.currentTimeMillis() < targ_time) {
      try {
	Thread.sleep(1000);
      } catch (InterruptedException e) {}
    }
    
    // close URLConnection

    if (ucon instanceof HttpURLConnection) {
      ((HttpURLConnection) ucon).disconnect();
      System.out.println("Disconnect attempted.");
    } else {
      System.out.println("Disconnect not attempted.");
    }
  }

}
